<?php
// +-------------------------------------------------------------------
// |
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Service\Goods;

use Think\Log;

class Goods extends \Service\Common\BaseModel
{
    protected $name = 'goods';
    protected $is_vip_t = 1;
    protected $is_vip_f = 0;

    public function formatCallback($data)
    {
        $goods = M('goods')->where(['id' => $data['goods.id']])->find();
        $list_cover_img = getcover($goods['list_cover']);
        $img = "<img src='{$list_cover_img}' style='width: 60px;'>";
        return [
            'goods.list_cover_img'=>$img,
        ];
    }

    //批量删除
    public function goodsDel($ids)
    {
        $array = explode(',',$ids);
        try {
            $this->startTrans();
            foreach ($array as $id) {
                M('goods')->delete($id);
                M('goods_sku')->where(['goods_id'=>$id])->delete();
            }
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new \Exception($e->getMessage());
        }
    }
    
    public function getTypeList()
    {
    	$list = M('poster')->where(['category'=>'goods_category'])
    	                   ->order('level asc,id asc')
    	                   ->select();
    	if ($list) {
    		foreach ($list as $k=>$v){
    			$list[$k]['pic_url'] = M('picture')->where(['id'=>$v['pic']])
    	                                           ->getField('url');
    		}
    	}
    	return $list;
    }
    //获取商品详情
    public function getDetail($goods_id, $uid = 0)
    {
        $result = $this->find($goods_id);

        if (!$result) {
            throw new \Exception('没有该商品');
        }


        return $this->format($result, $uid);
    }
    
    public function getGroupList2($page_num, $page_size, $uid = 0,$order = 'id',$mode = 'desc', $type)
    {
    	$str = '';
    	$str .= $order.' '.$mode;
    	if (trim($str,' ') == '') {
    		$str = 'id desc';
    	}
        $list = $this->where(['type' => $type, 'status' => 1, 'is_vip' => 2])->page($page_num,$page_size)->order($str)->select();
        foreach ($list as &$item){
            $item['list_cover'] = get_cover($item['list_cover'], 'url');
        }
    	return $list;
    }

    //获取每组分类商品列表
    public function getGroupList($page_size, $uid = 0, $is_vip = 0)
    {
        $page_size = $page_size ?: 5;
        $goods_type = M('poster')->where(['category' => 'goods_category', 'id' => 6])->order('level asc,id asc')->select();
        $result = [];
        foreach ($goods_type as $row) {
            $row['pic'] AND $row['pic'] = get_cover($row['pic'], 'path');
            $list = $this->where(['status' => 1,'is_display'=>1, 'is_vip' => $is_vip])
                ->page(1, $row['num'] ?: 2)
                ->order('sort desc')
                ->select();
            if($list){
                foreach ($list as $k=>$v){
                    $list[$k]['poster'] = get_cover($v['poster'], 'path');
                }
            }

            $result[] = array_merge($row, [
                'list' => $this->format($list, $uid)
            ]);
        }
        return $result;
    }

    public function getGroupList3($page_size, $uid = 0,$poster_id,$order = 'id',$mode = 'desc')
    {

        $result = [];
        $str = '';
        $str .= $order.' '.$mode;
        if (trim($str,' ') == '') {
            $str = 'id desc';
        } 
            $list = $this->where(['status' => 1,'is_vip' => $this->is_vip_t])
				                ->order($str)
				                ->select();
            foreach ($list as $k=>$v){
                $list[$k]['poster'] = get_cover($v['poster'], 'path');
            }
            $result[] =  [
                'list' => $this->format($list, $uid)
            ];

        return $result;
    }
    
    public function getIndexList($uid = 0, $is_vip = 0)
    {
    		$list = $this->where(['status' => 1,'is_display'=>1, 'is_vip' => $is_vip])->order('sort desc')->select();
    		foreach ($list as $k=>$v){
    			$list[$k]['poster'] = get_cover($v['poster'], 'path');
    		}
    	return $this->format($list, $uid);
    }

    //搜索
    public function search($keyword)
    {
        $list = $this->where([
            'title' => ['like', "%{$keyword}%"],
            'intro' => ['like', "%{$keyword}%"],
            '_logic' => 'OR'
        ])->select();
        return $this->format($list);
    }

    //格式化
    public function format($list, $uid = 0)
    {
        if (!$list) {
            return $list;
        }

        $is_one = count($list) == count($list, 1);
        $list = $is_one ? [$list] : $list;

        foreach ($list as &$row) {
            //复购价格
            $row['is_rebuy'] = 0;
            if ($uid) {
                $is_buy = M('user')->where(['uid' => $uid])->getField('vip_level') >= 1;
                $is_buy AND $row['contribution'] = $row['rebuy_contribution'];
                $is_buy AND $row['is_rebuy'] = 1;
            }

            $row['list_cover'] = get_cover($row['list_cover'], 'path');
            $picture_ids = array_filter(explode(',', $row['picture_ids']));
            $row['picture_urls'] = [];
            foreach ($picture_ids as $id) {
                $row['picture_urls'] [] = get_cover($id, 'path');
            }
        }
        return $is_one ? $list[0] : $list;
    }

    public function rushList($page_num, $page_size){
        $where = [
            'is_rush' => 1,
            'is_vip' => 2,
        ];
        $list = (array)$this->where($where)->order('sort desc')->page($page_num, $page_size)->select();
        $count = $this->where($where)->count();
        foreach($list as &$item){
            $item['list_cover'] = get_cover($item['list_cover'], 'url');
        }
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
        ];
    }

    public function goodsHotList($page_num, $page_size){
        $where = [
            'is_hot' => 1,
            'is_vip' => 2,
            'status' => 1,
        ];
        $list = (array)$this->where($where)->order('sort desc')->page($page_num, $page_size)->select();
        $count = $this->where($where)->count();
        foreach($list as &$item){
            $item['list_cover'] = get_cover($item['list_cover'], 'url');
        }
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
        ];
    }

    public function goodsReferList($page_num, $page_size){
        $where = [
            'is_refer' => 1,
            'is_vip' => 2,
            'status' => 1,
        ];
        $list = (array)$this->where($where)->order('sort desc')->page($page_num, $page_size)->select();
        $count = $this->where($where)->count();
        foreach($list as &$item){
            $item['list_cover'] = get_cover($item['list_cover'], 'url');
        }
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
        ];
    }

    public function goodsTypeList($page_num, $page_size , $param){
        if(!in_array($param['type'], ['rush', 'refer', 'hot']))
            throw  new \Exception('参数不正确');

        $where = [
            'is_'. $param['type'] => 1,
            'is_vip' => 2,
        ];
        $list = (array)$this->where($where)->order('sort desc')->page($page_num, $page_size)->select();
        $count = $this->where($where)->count();
        foreach($list as &$item){
            $item['list_cover'] = get_cover($item['list_cover'], 'url');
        }
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
        ];
    }

    public function BdGoodsList($page_num, $page_size , $param){


        $where = [
            'is_vip' => 1,
            'status' => 1,
        ];
        $list = (array)$this->where($where)->order('sort desc')->page($page_num, $page_size)->select();
        $count = $this->where($where)->count();
        foreach($list as &$item){
            $item['list_cover'] = get_cover($item['list_cover'], 'url');
        }
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
        ];
    }

    public function AgentGoodsList($page_num, $page_size , $param, $login_info){


        $where = [
            'is_agent' => 1,
            'status' => 1,
        ];
        $list = (array)$this->where($where)->order('sort desc')->page($page_num, $page_size)->select();
        $count = $this->where($where)->count();
        foreach($list as &$item){
            $item['list_cover'] = get_cover($item['list_cover'], 'url');
            /*if($login_info['vip_level'] == 0){

            }elseif($login_info['vip_level'] == 4){
                $item['sell_price'] = $item['agent_price'];
            }else{
                $item['sell_price'] = $item['vip_price'];
            }*/
        }
        return [
            $list,
            $page_count = $count,
            $page_total = ceil($count / $page_size),
        ];
    }

    public function goodsTwoTypeList($page_num, $page_size , $param){

        $category = M('goodstype')->where(['pid' => 0])->order('sort desc')->select();
        foreach ($category as &$item) {
            $two_category = (array)M('goodstype')->where(['pid' => $item['id']])->order('sort desc')->select();
            foreach ($two_category as &$item1) {
                $item1['pic'] = get_cover($item1['pic'], 'url');
            }

            $item['two_category'] = $two_category;

        }
        return [
            $category,
        ];

    }

    public function setGoodsSku($input,$goodsid,$type){

        $fuhe = 0;
        $dan = 0;
        $issku = 0;
        $zz = [];
        foreach ($input as $kk => $vv){
            if(strstr($kk,'sku')){
                //加入goods_sku
                if($vv>=0){
                    $issku = 1;
                }

                if(strstr($kk,'-0') && $vv >0){
                    $aaa = substr($kk,3);
                    $ap = M('sku')->where(['id'=>$aaa])->find();
                    $aaapid = $ap['pid'];
                    if(!in_array($aaapid,$zz)){
                        $dan += 1;
                        array_push($zz,$aaapid);
                    }
                }else{
                    if($vv){
                        $fuhe += 1;
                    }
                }
                if($dan > 1 ||($fuhe>=1 &&$dan == 1)){
                    throw  new \Exception('不支持当前操作');
                }

                $s = M('goods_sku')->where(['goods_id'=>$goodsid,'sku_ids'=> substr($kk,3)])->find();
                $nowtime = NOW_DATE_TIME;
                $sell_price_key = 'price1'.substr($kk,3);
                $vip_price_key = 'price2'.substr($kk,3);
                $agent_price_key = 'price3'.substr($kk,3);
                $adddata = ['goods_id'=>$goodsid,'sku_ids'=> substr($kk,3),'stock'=>$vv,'sell_price'=>$input[$sell_price_key],'vip_price'=>$input[$vip_price_key],'agent_price'=>$input[$agent_price_key],'create_time'=>$nowtime];
                $updata = ['update_time'=>$nowtime,'stock'=>$vv,'sell_price'=>$input[$sell_price_key],'vip_price'=>$input[$vip_price_key],'agent_price'=>$input[$agent_price_key]];
                if($s){
                    $add = M('goods_sku')->where(['id'=>$s['id']])->save($updata);
                }else{

                    if($vv >0){
                        $arr = explode('-',substr($kk,3));
                        $aa =[];
                        foreach ($arr as $value){
                            $a = M('sku')->where(['id'=>$value])->find();
                            $ai = ['pid'=>$a['pid'],'sku_id'=>$value];
                            if(!in_array($ai,$aa)){
                                array_push($aa,$ai);
                            }
                        }
                        $adddata['sku_content'] = json_encode($aa);
                        if($type == 1){
                            $add = M('goods_sku')->add($adddata);
                        }else{
                            throw  new \Exception('不支持当前操作');
                        }

                    }
                }
            }
        }
        if($issku ==0){
            throw  new \Exception('请填写规格');
        }
        if($add){
            return $goodsid;
        }else{
            return false;
        }

    }
}